package com.ItemsRent.IDao.dao;

import java.io.Serializable;
import java.util.List;



import org.hibernate.Session;
import org.hibernate.SessionFactory;



public class BaseDAO<T> {

	/**
	 * 
	 * 
	 * @param object
	 */
	private SessionFactory sessionFactory;
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public Session getSession(){
		if(sessionFactory.getCurrentSession()==null){
			return sessionFactory.openSession();
		}
			else return sessionFactory.getCurrentSession();
	}
	
	public void save(T object) {

		try {
			Session session = getSession();
			session.save(object);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * 
	 * @param object
	 */
	public void update(T object) {

		try {
			Session session = getSession();
			session.update(object);
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}

	/**
	 * 
	 * 
	 * @param object
	 */
	public void delete(T object) {

		try {
			Session session = getSession();
			session.delete(object);
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}

	/**
	 *
	 * 
	 * @param clazz
	 * @param id
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public T find(Class<? extends T> clazz, Serializable id) {

		
		try {
			Session session = getSession();
			return (T) session.get(clazz, id);
		} catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	 * 
	 * @param hql
	 * @return
	 */
	
	@SuppressWarnings("unchecked")
	public List<T> list(String hql) {
		try {
			Session session = getSession();	
			return session.createQuery(hql).list();
		} catch(Exception e){
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		return null;
	}
	
	public T find(String hql){
		try {
			Session session = getSession();
			@SuppressWarnings("unchecked")
			List<T> list = session.createQuery(hql).list();
			if(list!=null&&list.size()>0){
				return list.get(0);
			}else {
				return null;
			}
		} catch(Exception e){
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		return null;
	}
}